package com.example.demo.information.controller;

import com.alibaba.fastjson.JSON;
import com.example.demo.account.entity.SecurityUser;
import com.example.demo.account.entity.SysUserRole;
import com.example.demo.account.service.UserRoleService;
import com.example.demo.common.utils.*;
import com.example.demo.information.entity.Historyphoto;
import com.example.demo.information.entity.Photo;
import com.example.demo.information.entity.Student;
import com.example.demo.information.entity.info.StudentInfo;
import com.example.demo.information.service.HistoryPhotoService;
import com.example.demo.information.service.PhotoService;
import com.example.demo.information.service.StudentService;
import com.example.demo.param.entity.Param;
import com.example.demo.param.service.ParamService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class PhotoController {

    @Autowired
    private StudentService studentService;
    @Autowired
    private PhotoService photoService;
    @Autowired
    private HistoryPhotoService historyPhotoService;
    @Autowired
    private ImgUtils imgUtils;
    @Autowired
    private UserRoleService userRoleService;
    @Autowired
    private ParamService paramService;

    @RequestMapping("/resetPhoto")
    public String resetPhoto(){
        return "mobile/photoTake";
    }

    @RequestMapping("/stuPhotoDr")
    @ResponseBody
    public String stuPhotoDr(MultipartFile file){
        String message = "error";int code=1;//code 0 成功  1 失败
        Map<String,Object> map = new HashMap<>();
        map.put("data","");
        map.put("code",code);
        map.put("msg",message);
        String checkMsg = PhotoUtils.checkPhotoFile(file);
        if(!"true".equals(checkMsg)){
            map.put("msg",checkMsg);
            return JSON.toJSONString(map);
        }
        SecurityUser currentUserDetails = SpringSecurityUtils.getCurrentUserDetails();
        Student student = studentService.findBySfz(currentUserDetails.getUsername());
        try{
            String truePath = PhotoUtils.uploadImg(file);
            truePath = Constant.tempSaveFolder+truePath;
            File saveFile = new File(truePath);
            if(truePath==null||!saveFile.exists()){
                map.put("msg","文件保存失败");
                return JSON.toJSONString(map);
            }
            String spId = Constant.defaultPhotoParamSpid;
            String bkColor = Constant.defaultPhotoParamBkColor;
            Param photoParam = null;
            photoParam = student!=null&&student.getSchool()!=null?
                    paramService.findSchoolPhotoParam(student.getSchool().getId()):null;
            if(photoParam==null){
                photoParam = paramService.findByPzsmAndXxxxIdNull();
            }
            if(photoParam!=null){
                spId = photoParam.getPzz();
                bkColor = photoParam.getPzz2();
            }
            String resultSavePath = truePath.substring(0,truePath.lastIndexOf("."))
                    + "@@"+spId+"@@"+bkColor
                    + truePath.substring(truePath.lastIndexOf("."));

            WXAIPhotoAPI api = new WXAIPhotoAPI();
            String result = api.usePhotoAPI(truePath, spId, bkColor, resultSavePath);
            String internetPath = api.extractValueFromJsonString(result, "result");
            String status = api.extractValueFromJsonString(result, "status");

            System.out.println("truePath:"+truePath);
            System.out.println("resultSavePath:"+resultSavePath);
            System.out.println("InternetPath:"+internetPath);
            System.out.println("status:"+status);

            if (!"0".equals(status)) {
                System.out.println("bad status:" + status);
                map.put("msg","证件照生成失败,请联系管理员.");
                return JSON.toJSONString(map);
            }
            //String photoMsg = photoService.savePhotoByStudent(student,spId,bkColor
            //       ,truePath,resultSavePath,internetPath,currentUserDetails.getName());
            String photoMsg = historyPhotoService.saveTempPhotoByStudent(student,spId,bkColor
                    ,truePath,resultSavePath,internetPath,currentUserDetails.getName());
            if(!"success".equals(photoMsg)){
                map.put("msg","证件照保存失败.原因:"+photoMsg);
                return JSON.toJSONString(map);
            }
            map.put("code",0);
            map.put("msg","success");
            return JSON.toJSONString(map);
        } catch (Exception e) {
            e.printStackTrace();
            map.put("msg","生成证件照失败.");
            return JSON.toJSONString(map);

        }
    }

    @RequestMapping("/admitTempPhoto")
    @ResponseBody
    public String admitTempPhoto(@RequestParam("address") Long tempPhotoId){

        Historyphoto tempPhoto = historyPhotoService.findById(tempPhotoId);
        if(tempPhoto==null){
            return "证件照不存在，请重新拍摄。";
        }
        String message = photoService.saveHistoryPhoto(tempPhoto);
        return message;
    }

    /**
     * 加载图片  (正式使用的)
     * @param photoId
     * @param request
     * @param response
     */
    private void loadPhoto(Long photoId,HttpServletRequest request, HttpServletResponse response){
        String addressStr = "";
        String path = ClassUtils.getDefaultClassLoader().getResource("").getPath();
        addressStr = path + Constant.defaultPhotoPath;//默认图片toPhotoMake
        if (photoId != null) {
            Photo photo= photoService.findById(photoId);
            addressStr = photo!=null?photo.getSavepath():addressStr;
        }
        System.out.println("加载的图片路径："+addressStr);
        try {
            imgUtils.queryPic(addressStr,request,response);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("/getPhoto")
    @ResponseBody
    public void getPhoto(HttpServletRequest request, HttpServletResponse response) {
        loadPhoto(null,request,response);
    }

    @GetMapping("/getPhoto/{address}")
    public void getPhoto(@PathVariable("address") Long address
            ,HttpServletRequest request, HttpServletResponse response) {
        loadPhoto(address, request, response);
    }

    @RequestMapping("/getTempPhoto")
    @ResponseBody
    public void getTempPhoto(HttpServletRequest request, HttpServletResponse response) {
        loadTempPhoto(null,request,response);
    }

    @GetMapping("/getTempPhoto/{address}")
    public void getTempPhoto(@PathVariable("address") Long address
            ,HttpServletRequest request, HttpServletResponse response){
        loadTempPhoto(address,request,response);
    }

    /**
     * 加载图片  (历史拍摄记录)
     * @param photoId
     * @param request
     * @param response
     */
    private void loadTempPhoto(Long photoId, HttpServletRequest request, HttpServletResponse response) {
        String addressStr = "";
        String path = ClassUtils.getDefaultClassLoader().getResource("").getPath();
        addressStr = path + Constant.defaultPhotoPath;//默认图片toPhotoMake
        if (photoId != null) {
            Historyphoto historyPhoto = historyPhotoService.findById(photoId);
            addressStr = historyPhoto!=null?historyPhoto.getSavepath():addressStr;
        }
        System.out.println("加载的图片路径："+addressStr);
        try {
            imgUtils.queryPic(addressStr,request,response);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("/toPhotoMake")
    public String toPhotoMake(ModelMap map){
        SecurityUser currentUserDetails = SpringSecurityUtils.getCurrentUserDetails();
        SysUserRole role = userRoleService.findById(currentUserDetails.getCurrUserRoleId());
        if("1".equals(currentUserDetails.getLgType())&&role.getRole_id()== Constant.STUDENT_ID){
            Student student = studentService.findBySfz(currentUserDetails.getUsername());
            Historyphoto historyphoto= historyPhotoService.findByXsxxIdAndXxxxIdAndBjxxId(student.getId()
                    ,student.getSchool().getId(),student.getBjxx().getId());
            if(historyphoto!=null){
                map.addAttribute("address",historyphoto.getId());
            }
            return "mobile/photoMake";
        }else{
            return "index";
        }
    }

    @RequestMapping("/toPhoto")
    public String toPhoto(ModelMap map){
        List<Student> stuList = studentService.findAll();
        List<StudentInfo> stuInfoList = getStuInfoFromStu(stuList,Constant.defaultPhotoParamRatio,Constant.rangePhotoAll);
        int count = stuInfoList.size();
        stuInfoList = getCurrPage(stuInfoList,Constant.defaultParamCurr, Constant.defaultParamLimit);
        map.addAttribute("stuInfoList",stuInfoList);
        map.addAttribute("count",count);
        return "information/photo/photoList";
    }

    /**
     * 刷新页面的照片list
     * @param model
     * @param searchVal 搜索学生内容(姓名\身份证\学籍辅号)
     * @param id (xxId\bjId\xsId)
     * @param type (school\bjxx\student)
     * @param range 搜索照片范围(全部\已设置\未设置)
     * @return
     */
    @RequestMapping("/refrashPhoto")
    public String refrashPhoto(Model model, String searchVal,Long id,String type,@RequestParam("tab") String range
            ,Integer curr,Integer limit){
        List<Student> stuList = studentService.findByTypeAndSearch(searchVal,id,type);
        List<StudentInfo> stuInfoList = getStuInfoFromStu(stuList,Constant.defaultPhotoParamRatio,range);
        int count = stuInfoList.size();
        stuInfoList = getCurrPage(stuInfoList,curr,limit);
        model.addAttribute("stuInfoList",stuInfoList);
        model.addAttribute("count",count);
        return "information/photo/photoList::stu_PhotoPre";
    }

    /**
     * 获取当前页的数据
     * @param stuInfoList
     * @param curr
     * @param limit
     * @return
     */
    private List<StudentInfo> getCurrPage(List<StudentInfo> stuInfoList, Integer curr, Integer limit) {
        int num = 0,count = 0;
        if(curr==null||limit==null){
            return stuInfoList;
        }
        int currNum = (curr-1)*limit;
        List<StudentInfo> list = new ArrayList<>();
        for(StudentInfo s :stuInfoList){
            if(num>=currNum&&count<limit){
                list.add(s);
                count++;
            }
            num++;
        }
        return list;
    }

    /**
     * 获得学生对象(含照片信息)
     * @param studentList 需要查找的学生list
     * @param ratio 照片的大小比例
     * @param range 照片范围(全部\未设置\已设置)(选项卡)
     * @return
     */
    private List<StudentInfo> getStuInfoFromStu(List<Student> studentList,float ratio,String range){
        int width = Integer.valueOf(Constant.defaultPhotoParamWidth);
        int height = Integer.valueOf(Constant.defaultPhotoParamHeight);
        int newWidth = (int)((float)width * ratio);
        int newHeight = (int)((float)height * ratio);
        String widthStr = String.valueOf(newWidth);
        String heightStr = String.valueOf(newHeight);
        List<StudentInfo> list = new ArrayList<>();
        for(Student  s :studentList){
            StudentInfo stuInfo = new StudentInfo(s);
            Photo photo = photoService.findByXsxxIdAndXxxxIdAndBjxxId(s.getId(), s.getSchool().getId(), s.getBjxx().getId());
            if(photo!=null){
                stuInfo.setAddress(photo.getId());
            }
            stuInfo.setWidth(widthStr);
            stuInfo.setHeight(heightStr);
            if(StringUtils.isBlank(range)){//全部
                list.add(stuInfo);
            }else{
                if(Constant.rangePhotoSet.equals(range)&&photo!=null){//已设置
                    list.add(stuInfo);
                }else if(Constant.rangePhotoNoSet.equals(range)&&photo==null){//未设置
                    list.add(stuInfo);
                }
            }
        }
        return list;
    }

    @RequestMapping("/expStuPhoto")
    public void expStuPhoto(Long xxxxId,Long bjxxId,String xsIds,HttpServletResponse response){
        List<Student> stuList = studentService.getStuByXxxxIdBjxxIdXsIds(xxxxId,bjxxId,xsIds);
        if(stuList==null||stuList.isEmpty()){return;}
        try {
            photoService.downLoadStuPhoto(stuList,response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
